package developerworks.jetty6;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONException;

import developerworks.jetty6.UserServlet.Method;




public class TypingServlet extends HttpServlet {
	public void service(HttpServletRequest req, HttpServletResponse res) throws java.io.IOException {
		if(! Jabbify.filterVersion(req, res)) return;
		HttpSession session = req.getSession(false);
		if(session == null){
			res.getWriter().flush();
			System.out.println("No session for typing servlet");
			return;
		}
		
		switch(method(req)){
			case POST: create(req, res); break;
		}
	    res.setContentType("text/javascript");
	    String callback = req.getParameter("callback");

    	res.getWriter().print(callback+"({status: 201, errors: []})");
	    res.getWriter().flush();
	}
	public Method method(HttpServletRequest req){
		String method = req.getParameter("_method");
		if(method == null) method = req.getMethod();
		method = method.toLowerCase();
		if(method.compareTo("get") == 0) return Method.GET;
		if(method.compareTo("delete") == 0) return Method.DELETE;
		if(method.compareTo("put") == 0) return Method.PUT;
		return Method.POST;
	}
	public CrudMessage create(HttpServletRequest req, HttpServletResponse res) throws java.io.IOException {
		Typer u = new Typer(req.getParameter("user[call_id]"));
		u.create();
		u.sendTo("@"+ ApplicationAddressBook.getDomainName(req)  );
		return u;
	}
}
